﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DSheet.Core;
using DSheet.Core.CommonData;

namespace DExcelServiceApp
{
    public partial class BOrgList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (DBContext context = new DBContext())
                {
                    List<BOrg> orgs = new CommonDataService().GetOrgs(context);

                    _ctlListOrg.DataSource = orgs;
                    _ctlListOrg.DataBind();
                }
            }
        }

        protected void _ctlBtnSync_Click(object sender, EventArgs e)
        {
            using (DBContext context = new DBContext())
            {
                new CommonDataService().SyncBOrgToDim(context);
            }
        }

        protected void _ctlBtnCreate_Click(object sender, EventArgs e)
        {
            using (DBContext context = new DBContext())
            {
                BOrg newDomain = new BOrg();
                newDomain.Id = Guid.NewGuid();
                newDomain.Name = _ctlEditName.Text;
                if (!string.IsNullOrEmpty(_ctlHiddenParentId.Value))
                {
                    newDomain.ParentId = new Guid(_ctlHiddenParentId.Value);
                }
                new CommonDataService().SaveOrg(context, newDomain);

                List<BOrg> orgs = new CommonDataService().GetOrgs(context);

                _ctlListOrg.DataSource = orgs;
                _ctlListOrg.DataBind();

                new CommonDataService().SyncBDomainToDim(context);
            }
        }

        protected void _ctlListOrg_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Guid orgId = new Guid(e.CommandArgument.ToString());

            using (DBContext context = new DBContext())
            {
                BOrg org = new CommonDataService().GetOrg(context, orgId);
                _ctlHiddenParentId.Value = org.Id.ToString();
                _ctlEditParent.Text = org.Name;
            }
        }
    }
}